import asyncio
from tortoise import Tortoise
from app.core.config import settings
from app.core.security import get_password_hash
from app.models.models import User, Role, Department, Permission, RolePermission, UserRole

async def init_db():
    """初始化数据库连接"""
    await Tortoise.init(
        db_url=settings.DB_URL,
        modules={"models": ["app.models.models"]},
    )
    # 生成数据库表结构
    await Tortoise.generate_schemas()

async def create_initial_data():
    """创建初始数据"""
    # 创建部门
    root_dept = await Department.create(name="总公司", sort=1, status=True)
    tech_dept = await Department.create(name="技术部", parent_id=root_dept.id, sort=1, status=True)
    hr_dept = await Department.create(name="人事部", parent_id=root_dept.id, sort=2, status=True)
    finance_dept = await Department.create(name="财务部", parent_id=root_dept.id, sort=3, status=True)
    
    # 创建权限
    # 系统管理
    system_menu = await Permission.create(
        name="系统管理", 
        code="system", 
        type="menu", 
        path="/system", 
        component="Layout", 
        icon="setting", 
        sort=1, 
        status=True
    )
    
    # 用户管理
    user_menu = await Permission.create(
        name="用户管理", 
        code="system:user", 
        type="menu", 
        parent_id=system_menu.id, 
        path="user", 
        component="system/user/index", 
        icon="user", 
        sort=1, 
        status=True
    )
    
    user_query = await Permission.create(
        name="用户查询", 
        code="system:user:query", 
        type="button", 
        parent_id=user_menu.id, 
        sort=1, 
        status=True
    )
    
    user_create = await Permission.create(
        name="用户新增", 
        code="system:user:create", 
        type="button", 
        parent_id=user_menu.id, 
        sort=2, 
        status=True
    )
    
    user_update = await Permission.create(
        name="用户修改", 
        code="system:user:update", 
        type="button", 
        parent_id=user_menu.id, 
        sort=3, 
        status=True
    )
    
    user_delete = await Permission.create(
        name="用户删除", 
        code="system:user:delete", 
        type="button", 
        parent_id=user_menu.id, 
        sort=4, 
        status=True
    )
    
    # 角色管理
    role_menu = await Permission.create(
        name="角色管理", 
        code="system:role", 
        type="menu", 
        parent_id=system_menu.id, 
        path="role", 
        component="system/role/index", 
        icon="peoples", 
        sort=2, 
        status=True
    )
    
    role_query = await Permission.create(
        name="角色查询", 
        code="system:role:query", 
        type="button", 
        parent_id=role_menu.id, 
        sort=1, 
        status=True
    )
    
    role_create = await Permission.create(
        name="角色新增", 
        code="system:role:create", 
        type="button", 
        parent_id=role_menu.id, 
        sort=2, 
        status=True
    )
    
    role_update = await Permission.create(
        name="角色修改", 
        code="system:role:update", 
        type="button", 
        parent_id=role_menu.id, 
        sort=3, 
        status=True
    )
    
    role_delete = await Permission.create(
        name="角色删除", 
        code="system:role:delete", 
        type="button", 
        parent_id=role_menu.id, 
        sort=4, 
        status=True
    )
    
    # 部门管理
    dept_menu = await Permission.create(
        name="部门管理", 
        code="system:dept", 
        type="menu", 
        parent_id=system_menu.id, 
        path="dept", 
        component="system/dept/index", 
        icon="tree", 
        sort=3, 
        status=True
    )
    
    dept_query = await Permission.create(
        name="部门查询", 
        code="system:dept:query", 
        type="button", 
        parent_id=dept_menu.id, 
        sort=1, 
        status=True
    )
    
    dept_create = await Permission.create(
        name="部门新增", 
        code="system:dept:create", 
        type="button", 
        parent_id=dept_menu.id, 
        sort=2, 
        status=True
    )
    
    dept_update = await Permission.create(
        name="部门修改", 
        code="system:dept:update", 
        type="button", 
        parent_id=dept_menu.id, 
        sort=3, 
        status=True
    )
    
    dept_delete = await Permission.create(
        name="部门删除", 
        code="system:dept:delete", 
        type="button", 
        parent_id=dept_menu.id, 
        sort=4, 
        status=True
    )
    
    # 权限管理
    perm_menu = await Permission.create(
        name="权限管理", 
        code="system:perm", 
        type="menu", 
        parent_id=system_menu.id, 
        path="perm", 
        component="system/perm/index", 
        icon="lock", 
        sort=4, 
        status=True
    )
    
    # 日志管理
    log_menu = await Permission.create(
        name="日志管理", 
        code="system:log", 
        type="menu", 
        parent_id=system_menu.id, 
        path="log", 
        component="Layout", 
        icon="documentation", 
        sort=5, 
        status=True
    )
    
    # 请求日志
    request_log_menu = await Permission.create(
        name="请求日志", 
        code="system:log:request", 
        type="menu", 
        parent_id=log_menu.id, 
        path="request-log", 
        component="system/log/request-log", 
        icon="form", 
        sort=1, 
        status=True
    )
    
    request_log_query = await Permission.create(
        name="请求日志查询", 
        code="system:log:request:query", 
        type="button", 
        parent_id=request_log_menu.id, 
        sort=1, 
        status=True
    )
    
    # 登录历史
    login_history_menu = await Permission.create(
        name="登录历史", 
        code="system:log:login", 
        type="menu", 
        parent_id=log_menu.id, 
        path="login-history", 
        component="system/log/login-history", 
        icon="user", 
        sort=2, 
        status=True
    )
    
    login_history_query = await Permission.create(
        name="登录历史查询", 
        code="system:log:login:query", 
        type="button", 
        parent_id=login_history_menu.id, 
        sort=1, 
        status=True
    )
    
    perm_query = await Permission.create(
        name="权限查询", 
        code="system:perm:query", 
        type="button", 
        parent_id=perm_menu.id, 
        sort=1, 
        status=True
    )
    
    perm_create = await Permission.create(
        name="权限新增", 
        code="system:perm:create", 
        type="button", 
        parent_id=perm_menu.id, 
        sort=2, 
        status=True
    )
    
    perm_update = await Permission.create(
        name="权限修改", 
        code="system:perm:update", 
        type="button", 
        parent_id=perm_menu.id, 
        sort=3, 
        status=True
    )
    
    perm_delete = await Permission.create(
        name="权限删除", 
        code="system:perm:delete", 
        type="button", 
        parent_id=perm_menu.id, 
        sort=4, 
        status=True
    )
    
    # 创建角色
    admin_role = await Role.create(
        name="超级管理员", 
        code="admin", 
        description="超级管理员，拥有所有权限", 
        status=True
    )
    
    manager_role = await Role.create(
        name="管理员", 
        code="manager", 
        description="管理员，拥有大部分权限", 
        status=True
    )
    
    user_role = await Role.create(
        name="普通用户", 
        code="user", 
        description="普通用户，拥有基本权限", 
        status=True
    )
    
    # 分配权限
    # 超级管理员拥有所有权限
    all_permissions = await Permission.all()
    for perm in all_permissions:
        await RolePermission.create(role_id=admin_role.id, permission_id=perm.id)
    
    # 管理员拥有除了权限管理的所有权限
    all_perms = await Permission.all()
    manager_permissions = [perm for perm in all_perms if not perm.code.startswith("system:perm")]
    for perm in manager_permissions:
        await RolePermission.create(role_id=manager_role.id, permission_id=perm.id)
    
    # 普通用户只有查询权限
    user_permissions = await Permission.filter(code__endswith=":query").all()
    for perm in user_permissions:
        await RolePermission.create(role_id=user_role.id, permission_id=perm.id)
    
    # 创建用户
    admin_user = await User.create(
        username="admin",
        password=get_password_hash("admin123"),
        name="超级管理员",
        email="admin@example.com",
        phone="13800000000",
        avatar="https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
        status=True,
        department_id=root_dept.id
    )
    
    manager_user = await User.create(
        username="manager",
        password=get_password_hash("manager123"),
        name="管理员",
        email="manager@example.com",
        phone="13800000001",
        avatar="https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
        status=True,
        department_id=tech_dept.id
    )
    
    test_user = await User.create(
        username="test",
        password=get_password_hash("test123"),
        name="测试用户",
        email="test@example.com",
        phone="13800000002",
        avatar="https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
        status=True,
        department_id=hr_dept.id
    )
    
    # 分配角色
    await UserRole.create(user_id=admin_user.id, role_id=admin_role.id)
    await UserRole.create(user_id=manager_user.id, role_id=manager_role.id)
    await UserRole.create(user_id=test_user.id, role_id=user_role.id)
    
    print("初始数据创建成功！")

async def main():
    """主函数"""
    await init_db()
    await create_initial_data()
    await Tortoise.close_connections()

if __name__ == "__main__":
    asyncio.run(main())